import Tooltip from '@/components/Tooltip'
import { dictionaries } from '@/resources/dictionary'
import { currentChapterAtom, currentDictIdAtom } from '@/store'
import { Dialog, Transition } from '@headlessui/react'
import { useAtom, useSetAtom } from 'jotai'
import { atom } from 'jotai'
import { Fragment, useEffect, useState } from 'react'

const CATEGORY = '青少年英语'
const GROUP_SIZE = 20

// 新增：分组索引全局状态
export const currentDictGroupIndexAtom = atom<number>(0)

function getAllTags(dicts: any[]): string[] {
  const tagSet = new Set<string>()
  dicts.forEach((dict: any) => dict.tags.forEach((tag: string) => tagSet.add(tag)))
  return Array.from(tagSet)
}

export default function DictChapterButton() {
  const [isOpen, setIsOpen] = useState(false)
  const [selectedTag, setSelectedTag] = useState<string | null>(null)
  const [selectedDict, setSelectedDict] = useState<any>(null)
  const [selectedDictName, setSelectedDictName] = useState<string | null>(null)
  const [selectedGroupName, setSelectedGroupName] = useState<string | null>(null)
  const [currentDictId, setCurrentDictId] = useAtom(currentDictIdAtom)
  const [currentGroupIndex, setCurrentGroupIndex] = useAtom(currentDictGroupIndexAtom)
  const setCurrentChapter = useSetAtom(currentChapterAtom)

  // 只筛选 languageCategory=en 且 category为青少年英语的词典
  const filteredDicts = dictionaries.filter((dict: any) => dict.languageCategory === 'en' && dict.category === CATEGORY)

  // 所有tag
  const allTags = getAllTags(filteredDicts)

  // 当前tag下的所有教材
  const dictsByTag = selectedTag ? filteredDicts.filter((dict: any) => dict.tags.includes(selectedTag)) : []

  // 当前教材的分组
  const groupCount = selectedDict ? Math.ceil(selectedDict.length / GROUP_SIZE) : 0

  // 打开模态框时，根据当前词典ID和分组索引回填选中状态（只在首次打开时回填）
  useEffect(() => {
    if (isOpen && currentDictId) {
      const currentDict = filteredDicts.find((d) => d.id === currentDictId)
      if (currentDict) {
        const tag = currentDict.tags[0]
        setSelectedTag(tag)
        setSelectedDict(currentDict)
        // 回填分组名
        setSelectedGroupName(`第${currentGroupIndex + 1}组`)
      }
    }
  }, [isOpen])

  // 点击 tag 时，只设置 tag 并清空 dict
  const handleSelectTag = (tag: string) => {
    setSelectedTag(tag)
    setSelectedDict(null)
  }

  // 点击教材时，设置 selectedDict，并将分组索引重置为0
  const handleSelectDict = (dict: any) => {
    setSelectedDict(dict)
    setCurrentGroupIndex(0)
  }

  // 选择分组
  const handleSelectGroup = (groupIndex: number) => {
    if (!selectedDict) return
    setCurrentDictId(selectedDict.id)
    setSelectedDictName(selectedDict.name)
    setSelectedGroupName(`第${groupIndex + 1}组`)
    setCurrentGroupIndex(groupIndex)
    setCurrentChapter(groupIndex)
    setIsOpen(false)
  }

  // 返回上一级
  const handleBack = () => {
    setIsOpen(false)
  }

  // 页面加载时设置默认教材为"高考3500词"第一组
  useEffect(() => {
    if (!selectedDictName && !selectedGroupName && filteredDicts.length > 0) {
      const defaultDict = filteredDicts.find((dict: any) => dict.name.includes('高考3500'))
      if (defaultDict) {
        setCurrentDictId(defaultDict.id)
        setSelectedDictName(defaultDict.name)
        setSelectedGroupName('第1组')
      }
    }
  }, [filteredDicts, setCurrentDictId])

  // 每次 currentDictId 变化时，自动同步按钮显示内容
  useEffect(() => {
    if (currentDictId) {
      const dict = dictionaries.find((d: any) => d.id === currentDictId)
      if (dict) {
        setSelectedDictName(dict.name)
        if (!selectedGroupName) setSelectedGroupName('第1组')
      }
    }
  }, [currentDictId])

  return (
    <>
      <Tooltip content="词典切换">
        <button
          className="block rounded-lg border border-green-400 px-3 py-1 text-lg font-bold transition-colors duration-300 ease-in-out hover:bg-green-400 hover:text-white focus:outline-none dark:text-white dark:text-opacity-60 dark:hover:text-opacity-100"
          onClick={() => setIsOpen(true)}
        >
          {selectedDictName && selectedGroupName ? `${selectedDictName} - ${selectedGroupName}` : '词典切换'}
        </button>
      </Tooltip>
      <Transition appear show={isOpen} as={Fragment}>
        <Dialog as="div" className="relative z-50" onClose={handleBack}>
          <Transition.Child
            as={Fragment}
            enter="ease-out duration-300"
            enterFrom="opacity-0"
            enterTo="opacity-100"
            leave="ease-in duration-200"
            leaveFrom="opacity-100"
            leaveTo="opacity-0"
          >
            <div className="fixed inset-0 bg-black bg-opacity-25" />
          </Transition.Child>
          <div className="fixed inset-0 overflow-y-auto">
            <div className="flex min-h-full items-center justify-center p-4 text-center">
              <Transition.Child
                as={Fragment}
                enter="ease-out duration-300"
                enterFrom="opacity-0 scale-95"
                enterTo="opacity-100 scale-100"
                leave="ease-in duration-200"
                leaveFrom="opacity-100 scale-100"
                leaveTo="opacity-0 scale-95"
              >
                <Dialog.Panel className="flex h-[600px] w-auto min-w-[700px] max-w-[90vw] transform flex-col overflow-hidden rounded-2xl bg-white p-6 text-left align-middle shadow-xl transition-all dark:bg-gray-800">
                  <Dialog.Title as="h3" className="mb-4 text-lg font-medium leading-6 text-gray-900 dark:text-white">
                    选择单词
                  </Dialog.Title>
                  <div className="flex h-full min-w-full overflow-hidden rounded-lg border bg-gray-50 dark:bg-gray-900">
                    {/* 左侧：tag列表 */}
                    <div className="h-full min-w-[150px] max-w-[220px] flex-1 overflow-y-auto border-r border-gray-200 bg-white dark:border-gray-700 dark:bg-gray-900">
                      {allTags.map((tag) => (
                        <button
                          key={tag}
                          className={`w-full border-b border-gray-100 px-4 py-3 text-left text-base transition-colors dark:border-gray-800 ${
                            selectedTag === tag
                              ? 'bg-green-100 font-bold text-green-700 dark:bg-green-900'
                              : 'text-gray-700 hover:bg-green-50 dark:text-gray-200 dark:hover:bg-green-800'
                          }`}
                          onClick={() => handleSelectTag(tag)}
                        >
                          {tag}
                        </button>
                      ))}
                    </div>
                    {/* 中间：教材列表 */}
                    <div className="h-full min-w-[220px] max-w-[320px] flex-1 overflow-y-auto border-r border-gray-200 bg-white dark:border-gray-700 dark:bg-gray-900">
                      {selectedTag ? (
                        dictsByTag.length > 0 ? (
                          dictsByTag.map((dict: any) => (
                            <button
                              key={dict.id}
                              className={`w-full border-b border-gray-100 px-4 py-3 text-left text-base transition-colors dark:border-gray-800 ${
                                selectedDict && selectedDict.id === dict.id
                                  ? 'bg-green-100 font-bold text-green-700 dark:bg-green-900'
                                  : 'text-gray-700 hover:bg-green-50 dark:text-gray-200 dark:hover:bg-green-800'
                              }`}
                              onClick={() => handleSelectDict(dict)}
                            >
                              <div>{dict.name}</div>
                              <div className="text-xs text-gray-500 dark:text-gray-400">{dict.description}</div>
                            </button>
                          ))
                        ) : (
                          <div className="p-4 text-gray-400">无教材</div>
                        )
                      ) : (
                        <div className="p-4 text-gray-400">请选择分类</div>
                      )}
                    </div>
                    {/* 右侧：分组列表 */}
                    <div className="h-full min-w-[180px] max-w-[260px] flex-1 overflow-y-auto bg-white dark:bg-gray-900">
                      {selectedDict ? (
                        groupCount > 0 ? (
                          Array.from({ length: groupCount }).map((_, idx) => (
                            <button
                              key={idx}
                              className={`w-full border-b border-gray-100 px-4 py-3 text-left text-base text-gray-700 transition-colors hover:bg-green-50 dark:border-gray-800 dark:text-gray-200 dark:hover:bg-green-800 ${
                                currentGroupIndex === idx ? 'bg-green-100 font-bold text-green-700 dark:bg-green-900' : ''
                              }`}
                              onClick={() => handleSelectGroup(idx)}
                            >
                              <div className="font-bold text-green-700">第{idx + 1}组</div>
                              <div className="text-xs text-gray-500 dark:text-gray-400">
                                {`单词 ${idx * GROUP_SIZE + 1} - ${Math.min((idx + 1) * GROUP_SIZE, selectedDict.length)}`}
                              </div>
                            </button>
                          ))
                        ) : (
                          <div className="p-4 text-gray-400">无分组</div>
                        )
                      ) : (
                        <div className="p-4 text-gray-400">请选择教材</div>
                      )}
                    </div>
                  </div>
                  <div className="mt-4 flex justify-end">
                    <button
                      className="rounded bg-gray-200 px-4 py-2 text-gray-700 hover:bg-gray-300 dark:bg-gray-700 dark:text-gray-200 dark:hover:bg-gray-600"
                      onClick={handleBack}
                    >
                      关闭
                    </button>
                  </div>
                </Dialog.Panel>
              </Transition.Child>
            </div>
          </div>
        </Dialog>
      </Transition>
    </>
  )
}
